package com.ciei.dpagm.util;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

public class DataUtil {

    private static Pattern numberPattern = Pattern.compile("[+-]?\\d+(.\\d+)?");


    public static List<String[]> readData(File file, String splitVariable){
		List<String[]> list = new ArrayList<String[]>();
        try {
            String encoding = "UTF-8";
            if (file.isFile() && file.exists()) { 
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    String[] arr = lineTxt.split(splitVariable);
                    list.add(arr);
                }
                read.close();
                bufferedReader.close();
            } else {
                System.out.println("找不到文件");
            }
        } catch (Exception e) {
            System.out.println("出错了");
            e.printStackTrace();
        }
        return list;
	}
	
	public static Double toDouble(Object value) {
		if(value==null) {
			return null;
		}else {
			return Double.parseDouble(value.toString());
		}
	}
	
	public static String DataFormat(Double value,String formatStr) {
		if(value==null) {
			return null;
		}else {
			DecimalFormat df = new DecimalFormat(formatStr);
			return df.format(value);
		}
	}

    /**
     * 把list分成多个批次
     * @param list 数据集合
     * @param batchSize 每个批次的大小
     * @return	多个批次的map
     */
    public static<E> Map<Integer,List<E>> batchList(List<E> list, int batchSize){
        Map<Integer,List<E>> itemMap = new HashMap<>();
        itemMap.put(1,new ArrayList<>());
        for(E ele : list){
            List<E> batchList = itemMap.get(itemMap.size());
            if(batchList.size() == batchSize){
                //当batchList满足目标批次数量，则新建一个list存放后面的的元素
                batchList = new ArrayList<>();
                itemMap.put(itemMap.size()+1,batchList);
            }
            batchList.add(ele);
        }
        return itemMap;
    }

    /**
     * 比较两个Double是否相等
     * @param d1
     * @param d2
     * @return
     */
    public static boolean doubleIsEqual(Double d1,Double d2){
        if (d1 == null && d2 == null) {
            return true;
        }
        if (d1 != null && d2 != null) {
            return BigDecimal.valueOf(d1).compareTo(BigDecimal.valueOf(d2)) == 0;
        }
        return false;
    }

    /**
     *  将16进制字符串转换为字节数组
     * @param hexString 16进制字符串
     * @return 字节数组
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (StringUtils.isBlank(hexString)) {
            return null;
        }
        // 去掉所有空格，并转为大写
        //hexString = hexString.replaceAll(" ", "").toUpperCase();
        int length = hexString.length() / 2;
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            String hexSplit = hexString.substring(i * 2, i * 2 + 2);
            bytes[i] = (byte) Integer.parseInt(hexSplit, 16);
        }
        return bytes;
    }

    /**
     * 计算CRC16校验码
     *
     * @param checkBytes 需要计算的字节数组
     * @param littleEndian true：小端：低位在前（低地址），高位在后（高地址）<br>
     *                     false（默认）：大端模式（高位在低地址，高位在前，低位在后）
     * @return CRC16校验码
     */
    public static String getCrc16(byte[] checkBytes,boolean littleEndian) {
        if (checkBytes == null) {
            return "";
        }
        int crc = 0x0000ffff;
        int polynomial = 0x0000a001;

        int i, j;
        for (i = 0; i < checkBytes.length; i++) {
            crc ^= ((int) checkBytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((crc & 0x00000001) != 0) {
                    crc >>= 1;
                    crc ^= polynomial;
                } else {
                    crc >>= 1;
                }
            }
        }
        if (littleEndian) {
            // 高低位转换，低位在前，高位在后
            crc = ((crc & 0x0000FF00) >> 8) | ((crc & 0x000000FF) << 8);
        }
        String crcHex = Integer.toHexString(crc).toUpperCase();
        // 左侧补零
        return StringUtils.leftPad(crcHex, 4, '0');
    }
    /**
     * 字符串转16进制字符串
     * @param inputString 字符串
     * @return 16进制字符串
     */
    public static String stringToHexString(String inputString) {
        if (StringUtils.isBlank(inputString)) {
            return "";
        }
        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder hexString = new StringBuilder();
        byte[] inputBytes = inputString.getBytes();
        int bit;
        for (byte inputByte : inputBytes) {
            bit = (inputByte & 0x0f0) >> 4;
            hexString.append(chars[bit]);
            bit = inputByte & 0x0f;
            hexString.append(chars[bit]);
        }
        return hexString.toString().trim();
    }

    /**
     * 16进制字符串转字符串(无需Unicode解码)
     * @param hexString 16进制字符串
     * @return 字符串
     */
    public static String hexStringToString(String hexString) {
        String stringTemplate = "0123456789ABCDEF";
        char[] hexStringArray = hexString.toCharArray();
        byte[] bytes = new byte[hexString.length() / 2];
        int n;
        for (int i = 0; i < bytes.length; i++) {
            n = stringTemplate.indexOf(hexStringArray[2 * i]) << 4;
            n += stringTemplate.indexOf(hexStringArray[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * 在字符串的头部补位
     * @param input 需要补位的字符串
     * @param targetLength  补位后的最终长度
     * @param symbol symbol 如'0'
     * @return 补位后的字符串
     */
    public static String fill(String input,int targetLength,char symbol) {
        StringBuilder hexStringBuilder = new StringBuilder(input);
        while (hexStringBuilder.length() < targetLength) {
            hexStringBuilder.insert(0, symbol);
        }
        return hexStringBuilder.toString();
    }

    /**
     * 是否是数字
     * @param s
     * @return
     */
    public static boolean isNumber(String s) {
        return numberPattern.matcher(s).matches();
    }

    /**
     * 获取类型名称
     * @param value
     * @return
     */
    public static String getTypeName(Object value){
        if(value == null){
            return null;
        }
        String typeName = value.getClass().getTypeName();
        if(typeName.contains(".")){
            typeName = typeName.substring(typeName.lastIndexOf(".") + 1);
        }
        return typeName;
    }

    /**
     * 是否包含字符串
     * @param array
     * @param target
     * @return
     */
    public static boolean isContainsString(String[] array, String target) {
        for (String element : array) {
            if (element.equals(target)) {
                return true;
            }
        }
        return false;
    }
}